import { createApi } from "@reduxjs/toolkit/query/react"
import customFetchBase from "@/app/auth/authHeader"
import { setUser } from "@/app/user/userSlice"
import type { User } from "@/app/user/interfaces"
import type { RegisterInput } from "@/app/auth/interfaces"
import { UserResponse } from "@/app/auth/interfaces"
import { AuthEndpoints } from "@/app/consts"
import type { RequestNAnimalNCurator } from "@/app/animals/interfaces"
import qs from "qs"

export const userApi = createApi({
  reducerPath: "userApi",
  baseQuery: customFetchBase,
  tagTypes: ["User"],
  endpoints: builder => ({
    getMe: builder.query<User, null>({
      query() {
        return {
          url: "/users/me",
          credentials: "include",
        }
      },
      transformResponse: (result: User) => result,
      async onQueryStarted(_args, { dispatch, queryFulfilled }) {
        try {
          const { data } = await queryFulfilled
          dispatch(setUser(data))
        } catch (error) {}
      },
    }),
    updateUser: builder.mutation<
      User,
      Pick<User, "fullName" | "ownType" | "housingType" | "age" | "id">
    >({
      query: ({ id, ...credentials }) => ({
        url: `users/${id}`,
        method: "PUT",
        body: { ...credentials },
      }),
      async onQueryStarted(_args, { dispatch, queryFulfilled }) {
        const { data } = await queryFulfilled
        dispatch(setUser(data))
      },
    }),
    createRequest: builder.mutation<{ animal: string }, RequestNAnimalNCurator>(
      {
        query: ({ animal }) => ({
          url: `requests`,
          method: "POST",
          body: { data: { animal } },
        }),
      },
    ),
    getMyRequest: builder.query<RequestNAnimalNCurator, null>({
      query() {
        const search = qs.stringify(
          {
            populate: { animal: { populate: ["curator"] } },
          },
          {
            encodeValuesOnly: true, // prettify URL
          },
        )
        return {
          url: `/requests/my?${search}`,
          credentials: "include",
        }
      },
    }),
  }),
})

export const {
  useGetMeQuery,
  useCreateRequestMutation,
  useUpdateUserMutation,
  useGetMyRequestQuery,
} = userApi
